
/** 
 * SOAPClient4XG. Read the SOAP envelope file passed as the second
 * parameter, pass it to the SOAP endpoint passed as the first parameter, and
 * print out the SOAP envelope passed as a response.  with help from Michael
 * Brennan 03/09/01
 * 
 *
 * @author  Bob DuCharme
 * @version 1.1
 * @param   SOAPUrl      URL of SOAP Endpoint to send request.
 * @param   xmlFile2Send A file with an XML document of the request.  
 *
 * 5/23/01 revision: SOAPAction added
 */
import java.io.*;
import java.net.*;
import java.util.Calendar;
 
public class SOAPClient4XG {

    public static void main (String[] args) throws Exception {
        if (args.length < 2) {
            System.err.println("Usage:  java SOAPClient4XG " +
                    "http://soapURL soapEnvelopefile.xml" +
                    " [SOAPAction]");
            System.err.println("SOAPAction is optional.");
            System.exit(1);
        }
        String SOAPUrl = args[0];
        String xmlFile2Send = args[1];
        String SOAPAction = "";
        if (args.length > 2) {
            SOAPAction = args[2];
        //String[] parameters = new String[2];
//        FileInputStream fin = null ; //new FileInputStream();
//        String SOAPUrl = getParameter(args[0],fin); 
        // Create the connection where we're going to send the file.
        }
        URL url = new URL(SOAPUrl);
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConn = (HttpURLConnection) connection;
        // Open the input file. After we copy it to a byte array, we can see
        // how big it is so that we can set the HTTP Cotent-Length
        // property. (See complete e-mail below for more on this.)

        FileInputStream fin = new FileInputStream(xmlFile2Send); //ԭ

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        // Copy the SOAP file to the open connection.
        copy(fin, bout);
        fin.close();
        byte[] b = bout.toByteArray();
        // Set the appropriate HTTP parameters.
        httpConn.setRequestProperty("Content-Length",
                String.valueOf(b.length));
        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        httpConn.setRequestProperty("SOAPAction", SOAPAction);
        httpConn.setRequestMethod("POST");
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        // Everything's set up; send the XML that was read in to b.
        OutputStream out = httpConn.getOutputStream();
        out.write(b);
        out.close();
        // Read the response and write it to standard out.
        InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        outPrint(in);
    }
    // copy method from From E.R. Harold's book "Java I/O"

    public static void copy (InputStream in, OutputStream out)
            throws IOException {
        // do not allow other threads to read from the
        // input or write to the output while copying is
        // taking place
        synchronized (in) {
            synchronized (out) {
                byte[] buffer = new byte[256];
                while (true) {
                    int bytesRead = in.read(buffer);
                    if (bytesRead == -1) {
                        break;
                    }
                    out.write(buffer, 0, bytesRead);
                }
            }
        }
    }

    public static void outPrint (BufferedReader input) {
//===================复制对象===============================
//      BufferedReader input_copy = null ;
//      try {
//          ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//          ObjectOutputStream out = new ObjectOutputStream(byteOut);
//          out.writeObject(input);
//
//          ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
//          ObjectInputStream inPutStream = new ObjectInputStream(byteIn);
//          input_copy = (BufferedReader) inPutStream.readObject();
//      } catch (Exception e) {
//          e.printStackTrace();
//      }
//=======================复制失败==================================
        int i = -1;
        int int_ch;
        char lastCh = 'a';
        char ch;
        StringBuffer buff = new StringBuffer();
        BufferedReader in = input;
        try {
            int_ch = in.read();
            while (int_ch != -1) {
                ch = (char) int_ch;

                if (ch == '<') {
                    buff.append("\n");
                    for (int j = 0; j < i; j++) {
                        buff.append("  ");
                    }
                    buff.append(ch);
                    i++;
                } else if (ch == '>') {
                    buff.append(ch);
                    buff.append("\n");
                    if (lastCh == '/') {
                        i--;
                        buff.deleteCharAt(buff.lastIndexOf("<") - 2);
                        buff.deleteCharAt(buff.lastIndexOf("<") - 2);
                    }
                    for (int j = 0; j < i; j++) {
                        buff.append("  ");
                    }
                } else {

                    if (ch == '/' && lastCh == '<') {
                        buff.deleteCharAt(buff.length() - 2);
                        buff.deleteCharAt(buff.length() - 2);
                        i--;
                        i--;
                    }
                    buff.append(ch);
                }
                lastCh = ch;
                int_ch = in.read();
            }
        } catch (Exception e) {
            System.out.println("outPrint eror !");
        }
        Calendar calendar =  Calendar.getInstance();
        String printString = "现在时间是"+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND)+"\n";
        printString += buff.toString().replaceAll("\n\\s*\n", "\n");
        System.out.print(printString);

    }

    public static String getParameter (String xmlFilePath, FileInputStream fin) {
        StringBuffer buff = new StringBuffer();
        try {
            fin = new FileInputStream(xmlFilePath);
            //int int_ch = fin.read();
            char ch = (char) fin.read();
            while (ch != '\n') {
                buff.append(ch);
                ch = (char) fin.read();
            }
            fin.mark(buff.length());
            fin.reset();

        } catch (Exception e) {
            System.out.println("read file erroe !");
        }
        return buff.toString();
    }
}